#-*- coding:utf-8 -*-
import csv
import re
import types
import logging

logging.basicConfig()
log = logging.getLogger("recorder")


class JamongRecordFormat(object):
	def __init__(self):
		pass
	

	
class JamongRecord(object):
	titles_intro = (
			'time',
			'incapa',
			'operation',
			'incapa_cool',
			'hc_rate'
			)
	titles_unit1 = (
				'comp1',
				'comp2',
				'comp3',
				'liquid',
				'hotgas',
				'4way',
				'balance1',
				'balance2',
				'balance3',
				'cch1',
				'cch2', 
				'cch3',
				'maincool',
				'evi',
				'cch_acc',
				'odeev',
				'hpdown_30s',
				'ltdown_30s',
				'outfan_high',
				'hp_noup',
				'liquid_on',
				'hotgas_on',
				'sh0',
				'sh3',
				'sh6',
				's_discharge1',
				's_discharge2',
				's_discharge3',
				's_outtemp',
				's_eviin',
				's_eviout',
				'eev1',
				'eev2',
				'hreev',
				'lt',
				'fanstep',
				'evieev',
				'outcapa',
				's_highpress',
				's_lowpress',
				'opstatus',
				's_cond',
				's_oil',
				's_balance',
				's_doubletube',
				's_suction',
				'balance_step',
				'deice_step',
				'eev_source',
				'recovery_step',
				'safety_step',
				'off_step',
				'linejig',
				'prime_unit',			# Only this 2~!!!!!!
				'target_press',
				'press_rate'
				)
	titles_unit = (
				'comp1',
				'comp2',
				'comp3',
				'liquid',
				'hotgas',
				'4way',
				'balance1',
				'balance2',
				'balance3',
				'cch1',
				'cch2', 
				'cch3',
				'maincool',
				'evi',
				'cch_acc',
				'ODEEV',
				'HPdown_30s',
				'LTdown_30s',
				'outfan_high',
				'hp_noup',
				'liquid_on',
				'hotgas_on',
				'sh0',
				'sh3',
				'sh6',
				's_discharge1',
				's_discharge2',
				's_discharge3',
				's_outtemp',
				's_eviin',
				's_eviout',
				'eev1',
				'eev2',
				'hreev',
				'lt',
				'fanstep',
				'evieev',
				'outcapa',
				's_highpress',
				's_lowpress',
				'opstatus',
				's_cond',
				's_oil',
				's_balance',
				's_doubletube',
				's_suction',
				'balance_step',
				'deice_step',
				'EEV_source',
				'recovery_step',
				'safety_step',
				'off_step',
				'linejig',
				'press_rate',
				)
	titles_extra = (
				'recovery_ctime',
				'deice_ctime1',
				'deice_ctime2',
				'balance_ctime',
				'outcapa_sum',
				'capacontrol_source',
				'compcontrol_method',
				'componoff_status',
				'componoff_type',
				'lt_pid',
				'balance_unit_main',
				'balance_unit_sub1',
				'balance_unit_sub2',
				'balance_unit_sub3',
				's_ct1_u1',
				's_ct1_u2',
				's_ct1_u3',
				's_ct1_u4',
				's_ct2_u1',
				's_ct2_u2',
				's_ct2_u3',
				's_ct2_u4',
				's_ct3_u1',
				's_ct3_u2',
				's_ct3_u3',
				's_ct3_u4',
				)

	def __init__(self):
		self.record = []
		self.titles = []
		self.makeTitles()
	
	def makeTitles(self):
		titles = []
		titles.extend(self.titles_intro)
		titles.extend([x + "_u1" for x in self.titles_unit1])
		titles.extend([x + "_u2" for x in self.titles_unit])
		titles.extend([x + "_u3" for x in self.titles_unit])
		titles.extend([x + "_u4" for x in self.titles_unit])
		titles.extend(self.titles_extra)
		titles[titles.index("prime_unit_u1")] = "prime_unit"
		titles[titles.index("target_press_u1")] = "target_press"
		
		self.titles = titles
		self.titles_n = len(self.titles)
	
	def loadFile(self, filename):
		if self.record:
			del self.record
		self.record = []
		try:
			file = open(filename,"rb")
		except IOError:
			return False
		
		reader = csv.reader(file, 'excel-tab')
		
		try:
			while True:
				ln = reader.next()
				if len(ln) != self.titles_n:
					raise ValueError 
				self.record.append(ln)
		except StopIteration:
			pass
		except ValueError:
			del self.record
			self.record = []
		finally:
			file.close()

		# Title 라인이 있을 경우에는 제외함.
		if not self.record[0][0].startswith('200'):
			self.record.pop(0)
			
		return True
		
		
	def count(self):
		return len(self.record)
	
	def get(self, field, idx):
		return self.record[idx][self.titles.index(field)]
	
	def getTitles(self):
		return self.titles
	
	def getRecords(self):
		return self.record
	
	def getRecord(self, index):
		return self.record[index]
	
	def findall(self, tit, exp):
		""" Search item according to pattern
		"""
		p = re.compile(exp)
		result = [lnum 
				for lnum in range(self.count()) 
				if p.match(self.get(tit, lnum)) is not None]
		return result		
		
		
				

class Record(object):
	def __init__(self):
		pass
	
	
	
class Recorder(object):
	def __init__(self):
		pass
	
mantic = (("sensor", ">=", "70") , "AND", ("opstatus", "==", "off"))
man = ("80", "AND", "70")
mant = ("AND", ("==", "80",  "70"), ("==", "60", "50"))

def toExpression(query):
	a, b, c = query
	
	if isinstance(b, types.TupleType):
		val = toExpression(b)
	else:
		val = "(%s" % b
		
	val = val + "%s" % a
	
	if isinstance(c, types.TupleType):
		val = val + toExpression(c)
	else:
		if c.isdigit():
			val = val + "%s)" % c
		else:
			val = val + '\'%s\'' % c
		
	return val
	


def createQuery(operator, operand1, operand2):
	return (operator, operand1, operand2)

opstatus = 20
miles=501


query = createQuery(">=", "opstatus", "10")
query2 = createQuery("==", "miles", "500")
query = createQuery("and", query, query2)

print query
print toExpression(query)
print eval(toExpression(query))
